define(function(require, exports) {
	var util = require('util');
	var pubjs = require('pubjs');
	var $ = require('jquery');
	var view = require('@base/view');

	// dashboard基础模块
	var Base = view.container.extend({
		init: function(config) {
			config = pubjs.conf(config, {
				title: '',
				// String|Array 主题颜色, 标题取第一个颜色
				color: [],
				// 将block的配置属性转换为chart指定配置
				// eg: title -> label, 将当前block的title配置制指定为chart模块的label属性
				// 当属性值为 null、undefined、false时不传递
				configTransfer: {
					color: 'color',
					title: 'label'
				},
				module: '',
				config: {
				},

				url: '',
				data: null,
				param: null,
				auto_load: false,
				reqType: "websocket",
				reqMethod: "get"
			});

			var c = config.get();
			if (util.isString(c.color)) {
				c.color = [c.color];
			}

			this.$isReady = true;

			this.Super('init', arguments);
		},
		afterBuild: function() {
			var that = this;
			var c = that.getConfig();
			var container = that.getContainer();
			container.addClass('M-dashboardBlock');
			$([
				'<div class="M-dashboardBlockHead"></div>',
				'<div class="M-dashboardBlockBody"></div>',
				'<div class="M-dashboardBlockFoot"></div>'
			].join('')).appendTo(container);

			that.$doms = {
				head: container.find('.M-dashboardBlockHead'),
				body: container.find('.M-dashboardBlockBody'),
				foot: container.find('.M-dashboardBlockFoot').hide()
			}

			that.buildHead(that.$doms.head);
			that.buildFoot(that.$doms.foot);

			var defaultConfig = {
				target: that.$doms.body
			}
			util.each(c.configTransfer, function(value, prop) {
				if (!!value) {
					defaultConfig[value] = c[prop];
				}
			});
			that.createDelay('chart', c.module, util.extend(defaultConfig, c.config));

			that.createDelay(true, function() {
				that.$isReady = true;
				that.createReady();
				if (c.auto_load && c.url) {
					that.load();
				}

				if (c.data) {
					that.setData(c.data);
				}
			});
		},
		// 加载完成方法
		createReady: function() {

		},
		// 创建头部
		// 创建模块请用create或者createDelay方法
		buildHead: function(container) {
			return this;
		},
		buildFoot: function(container) {
			return this;
		},
		setParam: function(param, replace) {
			var c = this.getConfig();
			c.param = replace ? param : util.extend(c.param, param);

			if (this.$ && this.$.chart) {
				this.$.chart.setParam(param, replace);
			} else {
				c.config.param = util.extend(c.config.param, c.param);
			}

			return this;
		},
		reset: function() {
			this.$.chart.reset();
			return this;
		},
		load: function() {
			var c = this.getConfig();
			if (c.url) {
				this.showLoading();
				switch(c.reqType){
					case 'ajax':
						pubjs.data[c.reqMethod](c.url, c.param, this, 'onData');
					break;
					case 'websocket':
						pubjs.mc.send(c.url, c.param, this.onData.bind(this));
					break;
				}
			}
			return this;
		},
		onData: function(err, data) {
			this.hideLoading();
			if (err) {
				return pubjs.alert(err.message);
			}

			this.setData(data);
		},
		getData: function() {
			return this.$.chart.getData();
		},
		setData: function(data) {
			this.$data = data;
			this.$.chart.setData(data);
			return this;
		}
	});
	exports.base = Base;

	// 大标题模块
	var BigTitle = Base.extend({
		init: function(config) {
			config = pubjs.conf(config, {
				'class': 'M-dashboardBlockBigTitle'
			});
			this.Super('init', arguments);
		},
		buildHead: function(container) {
			var c = this.getConfig();
			container.css({
				'background': c.color[0]
			}).text(c.title);
		}
	});
	exports.bigTitle = BigTitle;

	// 不带指标切换的dashboard模块
	var Normal = Base.extend({
		init: function(config) {
			config = pubjs.conf(config, {
				'class': 'M-dashboardBlockNormal'
			});
			this.Super('init', arguments);
		},
		buildHead: function(container) {
			var c = this.getConfig();
			$('<i></i>').appendTo(container).css({
				'background': c.color[0]
			});
			$('<span></span>').appendTo(container).text(c.title);
			return this;
		}
	});
	exports.normal = Normal;

	// 有指标切换的dashboard模块
	var HasSwitch = Base.extend({
		init: function(config) {
			config = pubjs.conf(config, {
				'class': 'M-dashboardBlockHasSwitch',
				// 此处auto_load不可配置，必须为false
				'auto_load': false,
				'selectWidth': 100,
				'metrics': [
					{
						"field": "pageviews",
						"text": "展示量"
					}
				]
			});

			this.$switchFirst = true;
			this.Super('init', arguments);
		},
		switchMetric: function(met_id) {
			if (met_id)
			{
				this.setMetric(met_id);
			}

			// dropdown在设置默认值的时候会发送消息，此时chart还未创建，故不load数据
			if (this.$isReady) {
				this.reset().load();
			}
		},
		setMetric: function(met_id)
		{
			var c = this.getConfig();
			var cfg = c.config;
			var chartCfg;
			this.$currentMetric = util.find(c.metrics, met_id, 'field');

			if (this.$isReady) {
				chartCfg = this.$.chart.getConfig();
			} else {
				chartCfg = cfg;
			}

			chartCfg.yField = {
				field: this.$currentMetric.field,
				text: this.$currentMetric.text,
				format: this.$currentMetric.format || cfg.yField && cfg.yField.format || null
			};
			// 重新load数据
			this.setParam({
				metric: this.$currentMetric.field,
				sort:  this.$currentMetric.field + '|-1'
			});
			return this;
		},
		// 创建完成再加载数据
		createReady: function() {
			this.setMetric(this.$.select.getValue('id'));
		},
		onDropChange: function(ev) {
			if (ev.source === this.$.select) {
				// dropdown会在创建完成发送value消息，故第一次的消息不处理
				if (!this.$switchFirst) {
					this.switchMetric(ev.param.id);
				}
				this.$switchFirst = false;
				return false;
			}
		},
		buildHead: function(container) {
			var c = this.getConfig();
			$('<span></span>').appendTo(container).text(c.title);
			var select = $('<div></div>').appendTo(container);
			this.createDelay('select', '@base/common/drop.drop', {
				target: select,
				key: 'field',
				name: 'text',
				value: c.metrics[0].field,
				width: c.selectWidth,
				hasSearch: false,
				options: c.metrics
			});
		}
	});
	exports.hasSwitch = HasSwitch;

	// 有指标切换，且有加载更多的dashboard模块
	var HasSwitchLoadMore = HasSwitch.extend({
		init: function(config) {
			config = pubjs.conf(config, {
				param: {
					page: 1,
					size: 10
				}
			});
			this.Super('init', arguments);
		},
		reset: function() {
			var c = this.getConfig();
			c.param.page = 1;
			this.$doms.foot.hide();
			this.Super('reset', arguments);
			return this;
		},
		buildFoot: function(container) {
			this.uiBind($('<a href="" class="M-dashboardBlockLoadMore">' + LANG("加载更多...") + '</a>').appendTo(container), 'click', 'eventLoadMore')
		},
		eventLoadMore: function(evt) {
			evt.preventDefault();
			var c = this.getConfig();
			c.param.page += 1;
			this.load();
		},
		setData: function(data) {
			if (data) {
				var c = this.getConfig();
				// 没有更多则影藏加载按钮
				if (data.total / c.param.size <= data.page) {
					this.$doms.foot.hide();
				} else {
					this.$doms.foot.show();
				}
			}

			this.Super('setData', arguments);
			return this;
		}
	});
	exports.hasSwitchLoadMore = HasSwitchLoadMore;

	// 无标题的dashboard模块
	var NoTitle = Base.extend({
		init: function(config) {
			config = pubjs.conf(config, {
				'class': 'M-dashboardBlockNoTitle'
			});
			this.Super('init', arguments);
		},
		buildHead: function(container) {
			container.hide();
		}
	});
	exports.noTitle = NoTitle;

	// 有指标切换的lineBar模块
	var HasSwitchLineBar = Base.extend({
		init: function(config) {
			config = pubjs.conf(config, {
				'class': 'M-dashboardBlockHasSwitch',
				// 此处auto_load不可配置，必须为false
				'auto_load': false,
				'selectWidth': 100,
				// 默认的柱状指标
				'defaultMetric': "impressions",
				// 强制的默认排序
				'defaultSort': '',
				'metrics': [
					{
						"field": "session",
						"text": "会话数"
					}
				]
			});

			this.$switchFirst = true;
			this.Super('init', arguments);
		},
		switchMetric: function(met_id) {
			if (met_id)
			{
				this.setMetric(met_id);
			}

			// dropdown在设置默认值的时候会发送消息，此时chart还未创建，故不load数据
			if (this.$isReady) {
				this.reset().load();
			}
		},
		setMetric: function(met_id)
		{
			var c = this.getConfig();
			var cfg = c.config;
			var chartCfg;
			this.$currentMetric = util.find(c.metrics, met_id, 'field');

			if (this.$isReady) {
				chartCfg = this.$.chart.getConfig();
			} else {
				chartCfg = cfg;
			}

			chartCfg.yField[1] = {
				field: this.$currentMetric.field,
				text: this.$currentMetric.text,
				format: this.$currentMetric.format || cfg.yField && cfg.yField.format || null,
				type: this.$currentMetric.type || cfg.yField && cfg.yField.type || 'line',
				yAxisIndex: this.$currentMetric.yAxisIndex || cfg.yField && cfg.yField.yAxisIndex || '1'
			};
			
			// 折线的右边单位变化
			chartCfg.build.yAxis[1].axisLabel = util.extend({}, chartCfg.build.yAxis[1].axisLabel, {"formatter": this.$currentMetric.formatter || null});

			this.$.chart.setParam(chartCfg, true);

			var metrics = [c.defaultMetric, this.$currentMetric.field];
			// 重新load数据
			this.setParam({
				metrics: metrics,
				sort:  c.defaultSort || (this.$currentMetric.field + '|-1')
			});
			return this;
		},
		// 创建完成再加载数据
		createReady: function() {
			this.setMetric(this.$.select.getValue('id'));
		},
		onDropChange: function(ev) {
			if (ev.source === this.$.select) {
				// dropdown会在创建完成发送value消息，故第一次的消息不处理
				if (!this.$switchFirst) {
					this.switchMetric(ev.param.id);
				}
				this.$switchFirst = false;
				return false;
			}
		},
		buildHead: function(container) {
			var c = this.getConfig();
			$('<span></span>').appendTo(container).text(c.title);
			var select = $('<div></div>').appendTo(container);
			this.createDelay('select', '@base/common/drop.drop', {
				target: select,
				key: 'field',
				name: 'text',
				value: c.metrics[0].field,
				width: c.selectWidth,
				hasSearch: false,
				options: c.metrics
			});
		}
	});
	exports.hasSwitchLineBar = HasSwitchLineBar;
});